<?php
require_once (C_PATH . '/utility.php');
require_once (C_PATH . '/FirePHPCore/FirePHP.class.php');

/**
 * main
 * 
 * @package Controller  
 * @author Takuya Kanbara
 * @copyright Takuya Kanbara
 * @version 1.0
 * @access public
 */
class main extends spController
{
    var $tUsers;
	var $tUserConnection;

    /**
     * main::__construct()
     * 
     * @return
     */
    public function __construct()
    {
        parent::__construct();
        whoAmI($this); //check the permission
        
        $this->firephp = FirePHP::getInstance(true);
        
        //初始化模型类
        $this->tUsers = spClass('users');
			$this->tUserConnection = spClass('user_connection');
    }

    /**
     * main::index()
     * 
     * @return
     * @abstract 首页
     */
    function index()
    {
		if($this->user) {
			$this->dispatch();
            return;
		}
       $this->display('index.html');
    }
    
    /**
     * main::login()
     * 
     * @return
     * @abstract 登录
     */
    function login()
    {
        $data = $this->spArgs();
        $this->login_with_userdata($data);          
    }
    
    function logout()
    {
        $result = $this->tUsers->updateLoginDate($_COOKIE['last_login_date']); //更新上次登录时间
        if($result==-1)
        {
            echo '服务器出现错误，请点击后退按钮返回。';
            return;
        }
        else
        {
			$ip = get_real_ip();
			if($this->tUserConnection->find(array('conn_ip'=>$ip)))
			{
				$result = $this->tUserConnection->delete(array('conn_ip'=>$ip));
				if(!result)
				{
					 echo '服务器出现错误，请点击后退按钮返回。';
            		 return;
				}
			}
            setcookie('last_login_date', "", time() - 3600);
            setcookie('role',"", time() - 3600);
            setcookie('user_str', "", time() - 3600);
            $this->jump(spUrl('main', 'index'));
        }
    }
    
    function dispatch()
    {
        $user = $this->user;
        switch($user['userlevel'])
        {
            case 99:
                $this->jump(spUrl('unit_super', 'index'));
                break;
            case 50:
                $this->jump(spUrl('unit_school', 'index'));
                break;
            case 40:
                $this->jump(spUrl('unit_class', 'index'));
                break;
        }
        return;
    }
    
    function changeMyPwd()
    {
        $data = $this->spArgs();
        $id = $data['selectedUser'];
        $selectedUser = $this->tUsers->find(array('id'=>$id));
        $oldpwd = md5($selectedUser['pwdsalt'] . $data['oldpwd']);
        if($oldpwd != $selectedUser['pwd'])
            echo -1;    //密码错误
        else
        {
            $pwd = md5($selectedUser['pwdsalt'] . $data['pwd']);
            $this->tUsers->update(array('id'=>$id), array('pwd'=>$pwd));
            echo 1;     //修改成功
        }
    }
	
	function login_with_userdata($data)
	{
		if($data['remember_me']==1) $cookietime=time() + 3600*24*7;
        else $cookietime=0;  //如果不勾选，则设置cookie过期时间为浏览器进程
        
        $user = $this->tUsers->checkUsername($data['username']);
        if(!$user) {
            echo -1;  //无此用户名
            return;
        }
        $pwd = md5($user['pwdsalt'] . $data['pwd']);
        if($pwd != $user['pwd']) {
            echo -2;  //密码错误
            return;
        }
        
		//记录cookie
		ob_clean();ob_start();
        $result = setcookie('last_login_date', date('Y-m-d h:i:s'), $cookietime);
		if(!$result) {
			echo -3;  //cookie错误
			return;
		}
        $user_str = serialize($user);
		ob_clean();ob_start();
        $result = setcookie('user_str', $user_str, $cookietime);
		if(!$result) {
			echo -3;  //cookie错误
			return;
		}
		ob_clean();ob_start();
        $result = setcookie('role', $user['userlevel'], $cookietime);
		if(!$result) {
			echo -3;  //cookie错误
			return;
		}
		
		//记录用户本次登录数据，记录到数据库中，每次进行操作的时候都检查用户账户是否存在异常
		//如目前从cookie取到的信息和数据库中的信息不符，则判断为帐号异常
		$conn_data['conn_username'] = $user['username'];
		$conn_data['conn_userlevel'] = $user['userlevel'];
		$conn_data['conn_instanceids'] = $user['instanceids'];
		$conn_data['conn_pwd'] = $user['pwd'];
		$conn_data['conn_pwdsalt'] = $user['pwdsalt'];	//以上为直接从$user中可以获取的数据
		
		$conn_data['conn_ip'] = get_real_ip();
		$conn_data['conn_datetime'] = date('Y-m-d h:i:s');	//以上为根据客户当前状态计算出的数据
		
		if($this->tUserConnection->find(array('conn_ip'=>$conn_data['conn_ip'])))
			$result = $this->tUserConnection->update(array('conn_ip'=>$conn_data['conn_ip']), $conn_data);
		else
			$result = $this->tUserConnection->create($conn_data);
		if(!result) {
			echo -4;	//记录用户登录数据错误
			return;
		}
        
        echo 1; //登录成功Ajax通知
        return;                  
	}
}
